-- Copyright (c) 2024 Huawei Technologies Co., Ltd.
-- openUBMC is licensed under Mulan PSL v2.
-- You can use this software according to the terms and conditions of the Mulan PSL v2.
-- You may obtain a copy of Mulan PSL v2 at:
--         http://license.coscl.org.cn/MulanPSL2
-- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
-- EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
-- MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
-- See the Mulan PSL v2 for more details.

local log = require 'mc.logging'
local context = require 'mc.context'
local client = require 'bios.client'
local skynet = require 'skynet'

local Event = {}

local STATE_ERROR = 'PropertyValueError: Incorrect value of property State.'

local function add_event(param)
    local record
    local event_obj = client:GetEventsEventsObject()
    if not event_obj then
        log:error('[bios]get events object failed')
        return false
    end

    local ok, err = pcall(function ()
        record = event_obj:AddEvent_PACKED(context.new(), param):unpack()
    end)
    if not ok then
        local err_str = string.format('%s', err)
        if err_str == STATE_ERROR then
            log:info('[bios]event exist, no need add')
            return true
        end
        log:notice('[bios] add event(%s) fail, err: %s', record, err)
        return false
    end
    log:debug('[bios]add event(%s) successfully', record)
    return true
end

local RETRY_TIMES = 2
local function retry_add_event(param)
    for _ = 1, RETRY_TIMES do
        local ok, ret = pcall(add_event, param)
        if ok and ret then
            return true
        end
        skynet.sleep(50)
    end
    return false
end

--- 产生软件告警
function Event.generate_event(msg)
    local param = {}
    for key, value in pairs(msg) do
        param[#param + 1] = { key, value }
    end

    local res = retry_add_event(param)
    if not res then
        error('[bios]generate event fail')
    end
end

return Event